const userSQL = require('../db/userSQL')
const {db,pool}=require('../db/db')
const fs = require('fs')
const path = require('path')
const md5=require('blueimp-md5')

const getList = async s => {
  let result = await db(userSQL.queryAll, [])
  let data=JSON.stringify(result)
  const list = JSON.parse(data).filter(item => item.nickname.search(s) !== -1 || item.identity.search(s) !== -1)
  return list
}

const login = async (username, password) => {
  let result = await db(userSQL.queryAll, [])
  let data=JSON.stringify(result)
  return JSON.parse(data).filter(item => item.username === username && item.password === md5(password))[0]
}

const getUserByUsername = async username => {
  let result = await db(userSQL.queryAll, [])
  let data=JSON.stringify(result)
  return JSON.parse(data).find(item => item.username === username)
}

const register = async (username, password, nickname) => {
  let result = await db(userSQL.queryAll, [])
  let data=JSON.stringify(result)
  const users = JSON.parse(data)

  users.push({
    id: users.length ? users[users.length - 1].id - 0 + 1 : 1,
    username,
    password,
    nickname,
    identity: '学生',
    gender: '',
    age:null,
    createTime: new Date(),
    updateTime: new Date(),
    cart: '',
    admin_select:0
  })
  let val=users[users.length-1]
  pool.query(userSQL.insert, [val.id,val.username,md5(val.password),val.nickname,val.identity,val.gender,val.age,val.createTime,val.updateTime],(err,result)=>{undefined
    if(err) throw err;
    console.log(result);
  });
  return 'ok'

}

const getUserById = async id => {
  let result = await db(userSQL.queryAll, [])
  let data=JSON.stringify(result)
  return JSON.parse(data).find(item => item.id === id)
}

const update = async (id, username,gender, age, nickname) => {
  let result = await db(userSQL.queryAll, [])
  let data=JSON.stringify(result)
  const users = JSON.parse(data)
  const user = users.find(item => item.id === id)
  if(username) user.username=username
  if (gender) user.gender = gender
  if (nickname) user.nickname = nickname
  if (age) user.age = age
  user.updateTime = new Date()
  pool.query(userSQL.updateUser,[user.username,user.gender,user.nickname,user.age,user.updateTime,id],(err,result)=>{undefined
    if(err) throw err;
    console.log(result);
  });
  return 'ok'
}

const password = async (id, p) => {
  let result = await db(userSQL.queryAll, [])
  let data=JSON.stringify(result)
  const users = JSON.parse(data)
  const user = users.find(item => item.id === id)

  user.password = md5(p)
  user.updateTime = new Date()

  pool.query(userSQL.rePassword,[user.password,user.updateTime,user.username],(err,result)=>{undefined
    if(err) throw err;
    console.log(result);
  });
  return 'ok'
}

module.exports = {
  getList,
  login,
  getUserByUsername,
  register,
  getUserById,
  update,
  password
}
